package com.dycong.common.common;

import org.apache.log4j.Logger;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.Optional;

/**
 * Created by dycong on 2016/12/26.
 */
public class DateUtil {
    private static Logger logger = Logger.getLogger(DateUtil.class);
    static final Object NANO_TIMESTAMP_LOCK = new Object();

    public DateUtil() {
    }

    public static DateFormat getDateFormat(String format) {
        return new SimpleDateFormat(format);
    }

    public static String format(Date date, String formatString) {
        DateFormat dateFormat = getDateFormat(formatString);
        return dateFormat.format(date);
    }

    public static Optional<Date> parse(String dateString, String formatString) {
        DateFormat dateFormat = getDateFormat(formatString);

        try {
            return Optional.of(dateFormat.parse(dateString));
        } catch (ParseException var4) {
            logger.error("", var4);
            return Optional.empty();
        }
    }

    public static Date millionSecondsLater(long millionSecondsLater) {
        return new Date(System.currentTimeMillis() + millionSecondsLater);
    }

    public static LocalDateTime toLocalDateTime(Date date) {
        Instant instant = date.toInstant();
        return LocalDateTime.from(instant);
    }

    public static Date fromLocalDateTime(LocalDateTime localDateTime) {
        return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
    }

    public static long nanoTimestamp() {
        Object var0 = NANO_TIMESTAMP_LOCK;
        synchronized(NANO_TIMESTAMP_LOCK) {
            long ms = System.currentTimeMillis();
            long ns = System.nanoTime();
            return ms * 1000000L + ns % 1000000L;
        }
    }
}
